// <script src="http://cdn.sockjs.org/sockjs-0.3.min.js"></script>

var ws = null;
var urldefault = "ws://" + window.location.host + "/websck.do";
var urlsockjs = "ws://" + window.location.host + "/sockjs/websck.do";

var request = "request";
var response = "response";
var deleteFriend = "delete";

function connect() {
    if (!urldefault || !urlsockjs) {
        alert('url is null');
        return;
    }

    if ('WebSocket' in window) {
        ws= new WebSocket(urldefault);
    }else {
        ws = new SockJS(urlsockjs);
    }
    
    ws.onopen = function () {
    	layer.msg("连接服务器成功", {
			time : 1500
		});	
    };
    
    ws.onmessage = function (event) {
    	analysis(JSON.parse(event.data));
    };
    
    ws.onclose = function (event) {
    	layer.msg("服务器断开", {
			time : 1500
		});
    };
}

function request_friend(userId) {
	message = get_json(request, userId);
	
	sendJson(message);
}

function response_friend(userId) {
	message = get_json(response, userId);
	
	sendJson(message);
}

function delete_friend(userId) {
	message = get_json(deleteFriend, userId);
	
	sendJson(message);
}

function analysis(json) {
	if (json.head == "comfirm") {
		comfirm(json.body);
	} else if (json.head == "information") {
		information(json.body);
	} else if (json.head == "invite") {
        inviteMessage(json.body);
	} else if (json.head == "memberDispatch") {
        memberDispatch(json.body);
	} else if (json.head == "closeRoom") {
        closeRoom(json.body);
	} else if (json.head == "chatDispatch") {
        chatDispatch(json.body);
	}
}

function chatDispatch(json) {
    loadText(json.roomId, json.message);
}

function memberDispatch(json) {
    reloadRoomMember(json.roomId);
    loadText(json.roomId, json.message);
}

function inviteMessage(json) {
    $.messager.confirm("", json.message, function(r){
        if (r){
            $.post("/room/enterRoom.do", {
             	roomId : json.roomId
            });
            url = baseRoomUrl + "?roomId=" + json.roomId;
            f_addTab("聊天室"+json.roomId, json.roomId, "聊天室"+json.roomId, url);
        }
    });
}

function comfirm(json) {
	$.messager.confirm('好友请求', json.userName + '请求添加您为好友', function(r){
		if (r){
			response_friend(json.userId);
			layer.msg("回复已发出", {
    			time : 3000
    		});
		}
	});
}

function information(info) {
	layer.msg(info, {
		time : 3000
	});
}

function sendJson(json) {
	ws.send(JSON.stringify(json));
}

function get_json(head, body) {
	return {"head" : head, body : body};
}

